<template>
  <a-range-picker
    style="width: 300px"
    :disabled-date="disabledDate"
    v-bind="$attrs"
    @select="onSelect"
    @popup-visible-change="onPopupVisibleChange"
  />
</template>

<script lang="ts" setup>
  import { ref, withDefaults, defineEmits, defineProps } from 'vue';
  import dayjs from 'dayjs';
  import isBetween from 'dayjs/plugin/isBetween';

  interface Props {
    maxDay: number;
  }
  const props = withDefaults(defineProps<Props>(), {});
  const emit = defineEmits(['']);
  dayjs.extend(isBetween);

  const dates = ref<any[]>([]);

  const onSelect = (valueString: any, value: (Date | undefined)[]) => {
    dates.value = value;
  };

  const onPopupVisibleChange = (visible: boolean) => {
    if (!visible) {
      dates.value = [];
    }
  };

  const disabledDate = (current: Date) => {
    if (dates.value && dates.value.length) {
      const tooLate =
        dates.value[0] &&
        Math.abs(
          (new Date(current).getTime() - dates.value[0]) / (24 * 60 * 60 * 1000)
        ) >
          props.maxDay - 1;
      const tooEarly =
        dates.value[1] &&
        Math.abs(
          (new Date(current).getTime() - dates.value[1]) / (24 * 60 * 60 * 1000)
        ) >
          props.maxDay - 1;
      return tooEarly || tooLate;
    }
    return false;
  };
</script>

<style lang="less" scoped></style>
